package edu.zut.main.thread;

public class DeadThread {
    public static void main(String[] args) {
        People boy = new People("boy");
        People girl = new People("girl");
        new Thread(new DeadLockThread(boy)).start();
        new Thread(new DeadLockThread(girl)).start();
    }

}
class DeadLockThread implements Runnable{

    private People people;

    public DeadLockThread(People people) {
        this.people = people;
    }

    @Override
    public void run() {
        try {
            people.eat();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//刀 叉 模拟死锁
class Fork{}

class Knife{}

class People{

    //大家共享这一组刀叉
    static Fork fork = new Fork();
    static Knife knife = new Knife();

    private String name;
    People(String name){
        this.name = name;
    }
    //当锁定多个对象时，一定要注意不要死锁
    public void eat() throws InterruptedException {
        if (name.equals("boy")){
            synchronized (fork) {
                System.out.println("boy现在拿到了叉子");
            }
            Thread.sleep(500);
            synchronized (knife){
                System.out.println("boy又拿到了刀子");
            }
        }
        if (name.equals("girl")){
            synchronized (knife){
                System.out.println("girl拿到了刀");
            }
            Thread.sleep(500);
            synchronized (fork){
                System.out.println("girl又拿到了叉子");
            }
        }



    }



}





